<template>
    <div>
        <a-upload v-model:file-list="fileList" :accept="accept" :before-upload="beforeUpload" name="iFile" :action="uploadFileApi"
            :headers="headers" @change="handleChange">
            <a-button class="flex items-center">
                <upload-outlined></upload-outlined>
                <span>{{ uploadText }}</span>
            </a-button>
        </a-upload>
    </div>
</template>
<script lang="ts" setup>
import { ref, computed } from 'vue';
import { message, Upload } from 'ant-design-vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import type { UploadChangeParam, UploadProps } from 'ant-design-vue';
import { uploadFileApi } from '@/utils/api/file';
import useUserStore from '@/stores/user';
const userStore = useUserStore();

const prop = defineProps({
    modelValue: {
        type: String,
        default: ''
    },
    uploadText: {
        type: String,
        default: '上传'
    },
    accept: {
        type: String,
        default: '*'
    },
})

const emit = defineEmits(['update:modelValue', 'change'])

const value = computed({
    get: () => prop.modelValue,
    set: (value) => emit('update:modelValue', value)
})

const handleChange = (info: UploadChangeParam) => {
    if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
        value.value = info.file.response.data.url;
        message.success(`${info.file.name} file uploaded successfully`);
    } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
    }
};

const beforeUpload: UploadProps['beforeUpload'] = file => {
    const isPNG = file.type === 'image/png';
    if (!isPNG) {
        message.error(`${file.name} is not a png file`);
    }
    return isPNG || Upload.LIST_IGNORE;
};

const fileList = ref([]);
// 上传文件头
const headers = ref({
    Authorization: 'Bearer ' + userStore.token,
});
</script>